package com.lepu.app.usercenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.usercenter.bean.BeanPwdQuestion;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.usercenter.util.UserCenterUtil;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class ModifyPwdQuestionActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest {

	private static final String REQUEST_USER_PWD_QUESTION = "request_user_pwd_question";
	private static final String REQUEST_PWD_QUESTION = "request_pwd_question";
	private static final String REQUEST_OK = "request_ok";

	private static final int MSG_USER_PWD_QUESTION_SUCCESS = 10;
	private static final int MSG_USER_PWD_QUESTION_FAIL = 11;

	private static final int MSG_PWD_QUESTION_SUCCESS = 20;
	private static final int MSG_PWD_QUESTION_FAIL = 21;

	private static final int MSG_OK_SUCCESS = 30;
	private static final int MSG_OK_FAIL = 31;

	private ArrayList<BeanPwdQuestion> mDataList = null;
	private String[] mStringArray = null;
	private boolean mSettingPwdQuestion = false;
	
	private String mQuestion0Id = "0";
	private String mQuestion1Id = "0";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usercenter_modify_pwd_question_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("密保问题");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		EditText questionEditText1 = (EditText) findViewById(R.id.questionEditText1);
		EditText questionEditText2 = (EditText) findViewById(R.id.questionEditText2);

		questionEditText1.setFilters(new InputFilter[]{new EmojiFilter()});
		questionEditText2.setFilters(new InputFilter[]{new EmojiFilter()});
		
		boolean flag = MyApplication.getInstance().checkIsLogin();
		if (flag) {
			RelativeLayout questionLayout1 = (RelativeLayout) findViewById(R.id.questionLayout1);
			RelativeLayout questionLayout2 = (RelativeLayout) findViewById(R.id.questionLayout2);
			Button okButton = (Button) findViewById(R.id.okButton);

			questionLayout1.setOnClickListener(mOnClickListener);
			questionLayout2.setOnClickListener(mOnClickListener);
			okButton.setOnClickListener(mOnClickListener);

			TextView tipTextView = (TextView) findViewById(R.id.tipTextView);
			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			if (loginInfo.HasSecurityQuestion.equals("0")) {
				mSettingPwdQuestion = false;
				// 未设置
				tipTextView.setText("为避免遗忘,请您填写真实信息,这将帮助您以后通过回答问题快速找回密码");

				requestQuestions();
			} else {

				mSettingPwdQuestion = true;
				tipTextView.setText("请重新选择问题，并填写答案");

				requestUserQuestions();
			}
		}
	}

	/*
	 * 未设置时 获取所有密保问题
	 */
	private void requestQuestions() {
		boolean flag = UserCenterUtil.getPwdQuestion(this, this,
				REQUEST_PWD_QUESTION);
		if (flag) {
			showProgressDialog();
		}
	}

	/*
	 * 已设置 获取当前用户的密保问题
	 */
	private void requestUserQuestions() {
		
		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		boolean flag = UserCenterUtil.getPwdQuestionByPhone(this, this,
				REQUEST_USER_PWD_QUESTION, loginInfo.MobilePhone);
		if (flag) {
			showProgressDialog();
		}
	}
	
	private void requestOk() {

		//TextView questionTextView1 = (TextView) findViewById(R.id.questionTextView1);
		//TextView questionTextView2 = (TextView) findViewById(R.id.questionTextView2);
		EditText questionEditText1 = (EditText) findViewById(R.id.questionEditText1);
		EditText questionEditText2 = (EditText) findViewById(R.id.questionEditText2);

		// 1
		//String question1 = questionTextView1.getText().toString().trim();
		String question1Content = questionEditText1.getText().toString().trim();
		//String question2 = questionTextView2.getText().toString().trim();
		String question2Content = questionEditText2.getText().toString().trim();
		
		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		boolean flag = UserCenterUtil.getUpdateSecurityQuestion(this, this, REQUEST_OK, loginInfo.UserID,
				loginInfo.LoginToken, mQuestion0Id, question1Content,
				mQuestion1Id, question2Content);
		if(flag)
		{
			showProgressDialog();
		}
	}

	
	private void updateQuestionText(final int index) {
		if (mDataList != null && mDataList.size() > 0) {

			final int totalCount = mDataList.size();
			//int totalCount = 13;//test
			mStringArray = null;
			
			int count = 0;
			if (index == 0) {
				count = totalCount / 2;
				mStringArray = new String[count];
				
				for(int i=0;i<count;i++)
				{
					mStringArray[i] = mDataList.get(i).Question;
				}
			} else {
				int startCount = totalCount / 2;
				count = totalCount - startCount;
				mStringArray = new String[count];
				
				for(int i=0;i<count;i++)
				{
					mStringArray[i] = mDataList.get(i+startCount).Question;
				}
			}

			new MyDialog(ModifyPwdQuestionActivity.this)
					.setSimpleItems(mStringArray,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									
									String question = mStringArray[which];
									if(index == 0)
									{
										mQuestion0Id = mDataList.get(which).SQID;
										
										TextView questionTextView1 = (TextView) findViewById(R.id.questionTextView1);
										questionTextView1.setText(question);
									}else{
										int startCount = totalCount / 2;
										mQuestion1Id = mDataList.get(which+startCount).SQID;
										
										TextView questionTextView2 = (TextView) findViewById(R.id.questionTextView2);
										questionTextView2.setText(question);
									}
								}
							}).create(null).show();

		} else {
			
			if(mSettingPwdQuestion)
			{
				requestUserQuestions();
			}else{
				requestQuestions();
			}
		}
	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.questionLayout1:

				updateQuestionText(0);
				break;
			case R.id.questionLayout2:

				updateQuestionText(1);
				break;
			case R.id.okButton:

				requestOk();
				break;

			default:
				break;
			}
		}
	};

	private void getUserPwdQuestionSuccess()
	{
		if(mDataList != null && mDataList.size() > 0)
		{
			TextView questionTextView1 = (TextView) findViewById(R.id.questionTextView1);
			TextView questionTextView2 = (TextView) findViewById(R.id.questionTextView2);
			
			questionTextView1.setText(mDataList.get(0).Question);
			questionTextView2.setText(mDataList.get(1).Question);
			
			mQuestion0Id = mDataList.get(0).SQID;
			mQuestion1Id = mDataList.get(1).SQID;
		}else{
			// 未设置密保问题
			new MyDialog(ModifyPwdQuestionActivity.this)
					.setMessage("未设置密保问题，请使用其它方式找回!")
					.setNegativeButtonSplitImageHide(true)
					.setPositiveButton(R.string.app_ok,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {

								}
							}).create(null).show();
		}
	}
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_USER_PWD_QUESTION_SUCCESS:
				hideProgressDialog();

				getUserPwdQuestionSuccess();
				
				requestQuestions();
				break;
			case MSG_USER_PWD_QUESTION_FAIL:
				hideProgressDialog();
				break;
			case MSG_PWD_QUESTION_SUCCESS:
				hideProgressDialog();
				
				
				break;
			case MSG_PWD_QUESTION_FAIL:
				hideProgressDialog();
				break;
			case MSG_OK_SUCCESS:
				hideProgressDialog();
				
				LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
				loginInfo.HasSecurityQuestion = "1";
				LoginInfo.saveLoginInfo(ModifyPwdQuestionActivity.this, loginInfo);
				
				finish(true);
				break;
			case MSG_OK_FAIL:
				hideProgressDialog();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_USER_PWD_QUESTION)) {

			mDataList = BeanPwdQuestion.parseJsonData((String) data);
			mHandler.sendEmptyMessage(MSG_USER_PWD_QUESTION_SUCCESS);
		} else if (object.equals(REQUEST_PWD_QUESTION)) {

			mDataList = BeanPwdQuestion.parseJsonData((String) data);
			mHandler.sendEmptyMessage(MSG_PWD_QUESTION_SUCCESS);
		} else if (object.equals(REQUEST_OK)) {

			String result = (String) data;
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (code == 200) {
				mHandler.sendEmptyMessage(MSG_OK_SUCCESS);
			} else {
				mHandler.sendEmptyMessage(MSG_OK_FAIL);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_USER_PWD_QUESTION)) {
			mHandler.sendEmptyMessage(MSG_USER_PWD_QUESTION_FAIL);
		} else if (object.equals(REQUEST_PWD_QUESTION)) {
			mHandler.sendEmptyMessage(MSG_PWD_QUESTION_FAIL);
		} else if (object.equals(REQUEST_OK)) {
			mHandler.sendEmptyMessage(MSG_OK_FAIL);
		}
	}

}
